package se.thoka.twt.client.utils;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author Thobias Karlsson, Thoka
 * @since 9 jan 2010
 * @param <E> The list item type
 */
@SuppressWarnings("serial")
public class UniqueList<E> extends ArrayList<E> {
	/**
	 * Creates a new instance of {@link UniqueList}
	 */
	public UniqueList() {
	}

	/**
	 * Creates a new instance of {@link UniqueList}
	 * 
	 * @param elements The initial elements
	 */
	public UniqueList(Collection<E> elements) {
		addAll(elements);
	}

	@Override
	public boolean add(E e) {
		return !contains(e) ? super.add(e) : false;
	}

	@Override
	public void add(int index, E element) {
		if (!contains(element)) {
			super.add(index, element);
		}
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		boolean anyAdded = false;
		for (E e : c) {
			if (add(e)) {
				anyAdded = true;
			}
		}

		return anyAdded;
	}

	@Override
	public boolean addAll(int index, Collection<? extends E> c) {
		boolean anyAdded = false;
		for (E o : c) {
			if (!contains(o)) {
				super.add(index, o);
				anyAdded = true;
			}
		}

		return anyAdded;
	}

	@Override
	public E set(int index, E element) {
		int preIdx = indexOf(element);
		E preObj = super.set(index, element);
		if (preIdx != index) {
			remove(preIdx);
		}

		return preObj;
	}
}
